import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {ModalDirective} from 'ngx-bootstrap';
import {TagList, TagInfo, AddTag, EditTag, AddActivity, EditActivity} from '../banner/tag';
import {CouponsService} from '../../lib/service/admin/coupons.service';
import {BannerService} from '../banner/banner.service';
import {AdOssUploadService} from '../../lib/service/ad-oss-upload.service';
import {NzMessageService} from 'ng-zorro-antd';
import {AliyunOssOutputUrl} from '../../../config/api';
import {CategoryService} from '../category/category.service';

@Component({
  selector: 'system',
  templateUrl: './system.component.html',
  styleUrls: ['./system.component.scss'],
  providers: [CouponsService, BannerService, CategoryService]
})
export class SystemComponent implements OnInit {
  _disabledButton = true;
  _allChecked = false;
  _indeterminate = false;
  _displayData = [];
  _checkedNumber = 0;
  selectedMultipleOption = [{value: '1', label: '开启'}];

  totalItems: number;
  currentPage = 1;
  itemsPerPage = 10;
  name: string;
  model: string;
  orderField: string;
  orderSort: string;
  type: string;
  message: string;
  isShow = false;
  addActivity = new AddActivity();
  editActivity = new EditActivity();


  fileList = [];
  picList = [];
  fileList1 = [];
  picList1 = [];
  taskList = [];
  typeList = [];

  task_ids = [];
  checkedTaskInfo = [];
  taskModalVisible = false;
  taskPage = 1;
  taskPageSize = 5;
  taskTotal = 0;
  isConfirmTaskLoading = false;
  taskLoading = false;
  activityList = [];
  submitStatus = false;
  confirmStatus = null;
  confirmId = null;
  confirmTitle = '';
  _isSpinning = false;
  categories = [];


  @ViewChild('addModal') public addModal: ModalDirective;
  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('confirmModal') public confirmModal: ModalDirective;

  constructor(
    private router: Router,
    private couponsService: CouponsService,
    private bannerService: BannerService,
    private adOssUploadService: AdOssUploadService,
    private _message: NzMessageService,
    private categoryService: CategoryService
  ) {
    this.name = '';
    this.model = '';
    this.orderField = '';
    this.orderSort = '';
  }

  ngOnInit() {
    this.categoryService.getCategoryList(1, 0).subscribe(res => {
      if (res.code === 200) {
        this.categories = res.data;
        this.getActivityList(1);
      }
    });
  }

  picError = false;
  picError1 = false;

  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  fileChange1() {
    if (this.fileList1.length == 0 && this.picList1.length == 0) {
      this.picError1 = true;
    } else {
      this.picError1 = false;
    }
  }

  cancel() {
    this.addModal.hide();
  }

  showAddModal() {
    this.addModal.show();
  }

  showEditModal() {
    this.editModal.show();
  }

  addTask(e) {
    this.taskModalVisible = true;
  }

  getTaskList() {
    this.bannerService.getTaskList(this.taskPage, this.taskPageSize).subscribe(res => {
      if (res.code === 200) {
        const data = res.data;
        this.taskList = data.list.data;
        this.taskTotal = data.list.total;
        const task_type = data.task_type;
        for (const key in  task_type) {
          this.typeList.push({
            'label': task_type[key],
            'value': key
          });
        }
        ;
        this.taskList.map((e, i) => {
          e['taskPreview'] = `${AliyunOssOutputUrl}/${e['task_content']['image']}?update=${new Date().getTime()}`;
          e['checked'] = false;
          if (this.checkedTaskInfo.length > 0) {
            this.checkedTaskInfo.map((e1, i1) => {
              if (e.id === e1.id) {
                e['checked'] = true;
              }
            });
          }
        });
      }
    });
  }

  getActivityList(page) {
    this._isSpinning = true;
    this.bannerService.getActivityList(page, this.itemsPerPage).subscribe(res => {
      if (res.code == 200) {
        this._isSpinning = false;
        this.activityList = res.data.data;
        this.totalItems = res.data.total;
        this.activityList.map((e, i) => {
          if (e.pic) {
            e.pic = `${AliyunOssOutputUrl}/${e.pic}?update=${new Date().getTime()}`
          }
          if (this.categories.length > 0) {
            this.categories.forEach((e1, i1) => {
              if (e1.id === e.first_category_id) {
                e['category_name'] = e1['category_name'];
              }
            });
          }
        });
      }
    });
  }

  showConfirmModal(id, title, status) {
    this.confirmModal.show();
    this.confirmStatus = status;
    this.confirmId = id;
    this.confirmTitle = title;
  }


  closeConfirmModal() {
    this.confirmModal.hide();
  }

  changeStatus() {
    this.bannerService.changeStatus({'status': this.confirmStatus, 'id': this.confirmId}).subscribe(res => {
      if (res.code === 200) {
        this.confirmModal.hide();
        this.type = 'success';
        this.message = '修改状态成功!';
        this.isShow = true;
        setTimeout(() => {
          this.getActivityList(this.currentPage);
        }, 300);
      }
    })
  }

  closeTaskModal() {
    this.taskModalVisible = false;
  }

  goActivity() {
    // this.taskModalVisible = true;
    this.router.navigate(['tuike/system/add']);
  }


  dealTask(e, data) {
    this.taskList.map((item, i) => {
      if (item.id == data.id) {
        if (this.task_ids.length == 0) {
          if (e) {
            item['checked'] = true;
            this.task_ids.push(data);
          }
        } else {
          if (e) {
            let num = 0;
            this.task_ids.map((item1, i) => {
              if (item1.id != data.id && num === 0) {
                item['checked'] = true;
                this.task_ids.push(data);
                num++;
              }
              return;
            });
          } else {
            this.task_ids.map((item2, i) => {
              if (item2.id == data.id) {
                item['checked'] = false;
                this.task_ids.splice(i, 1);
                return;
              }
              return;
            });
          }
        }
      }
    });
    this.checkedTaskInfo = this.task_ids;
  }

  delete() {
    this.bannerService.deleteActivity({id: this.confirmId}).subscribe(res => {
      if (res.code === 200) {
        this.confirmModal.hide();
        this.type = 'success';
        this.message = '删除成功';
        this.isShow = true;
        setTimeout(() => {
          this.getActivityList(1);
        }, 300);
      }
    })
  }

  uploadImg(activity_id) {
    this.adOssUploadService
      .getSignature('/v1/admin/tuike_activity/' + activity_id + '?callback=true')
      .subscribe(
        res1 => {
          const length = this.fileList.filter(item => {
            return item && item != 'pic';
          }).length;
          let successLen = 0;
          if (length == 0) {
            // this.submitStatus = false;
            this._message.create('success', '添加成功');
            return false;
          }
          this.fileList.every((val, idx, array) => {
            if (val && val != 'pic') {
              this.adOssUploadService.fileUpload(val, res1.data, 'tuike_activity_pic' + '.' + val.name.replace(/.+\./, '').toLowerCase(), 'image')
                .subscribe(res2 => {
                    successLen++;
                    if (successLen == length) {
                      this.submitStatus = false;
                      this._message.create('success', '添加成功');
                      this.addModal.hide();
                      this.getActivityList(1);
                    }
                  }
                );
            }
            return true;
          });
        }
      );
  }

  addActivityFormSubmit(e) {
    e.stopPropagation();
    if (this.checkedTaskInfo.length == 0) {
      this.isShow = false;
      this.message = '请添加任务';
      this.type = 'error';
      return;
    }
    let data = Object.assign(this.addActivity);
    data['task_ids'] = [];
    this.checkedTaskInfo.map((e, i) => {
      data['task_ids'].push(e.id);
    });
    this.submitStatus = true;
    this.bannerService.addActivity(data).subscribe(res => {
      if (res.code == 200) {
        let id = res.data.id;
        this.uploadImg(id);
      }
    })
  }


  goEdit(id) {
    this.router.navigate(['tuike/activity/add'], {
      queryParams: {
        id: id
      }
    });
  }


  editActivityFormSubmit(e) {
    e.stopPropagation();
    if (this.checkedTaskInfo.length == 0) {
      this.isShow = false;
      this.message = '请添加任务';
      this.type = 'error';
      return;
    }
    let data = Object.assign(this.addActivity);
    data['task_ids'] = [];
    this.checkedTaskInfo.map((e, i) => {
      data['task_ids'].push(e.id);
    });
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.currentPage = event.page;
    this.getActivityList(this.currentPage);
  }

  promptIsShow(event: any): void {
    this.isShow = event;
  }

  _displayDataChange($event) {
    this._displayData = $event;
    this._refreshStatus();
  };

  _refreshStatus() {
    const allChecked = this.activityList.every(value => value.checked === true);
    const allUnChecked = this.activityList.every(value => !value.checked);
    this._disabledButton = !this.activityList.some(value => value.checked);
    this._checkedNumber = this.activityList.filter(value => value.checked).length;
    this._allChecked = allChecked;
    this._indeterminate = (!allChecked) && (!allUnChecked);
  };

  _checkAll(value) {
    if (value) {
      this.activityList.forEach(data => {
        data.checked = true;
      });
    } else {
      this.activityList.forEach(data => {
        data.checked = false;
      });
    }
    this._refreshStatus();
  };


  onStatus(i) {
    console.log('i', i);
    if (this.activityList[i].type === 1) {
      this.activityList[i].type = 0;
    } else if (this.activityList[i].type === 0) {
      this.activityList[i].type = 1;
    }
  }

  optionsOpen() {

    this.activityList.forEach(data => {
      if (data.checked === true) {
        data.type = 1;
      }
    });

  }

  optionsClose() {
    this.activityList.forEach(data => {
      if (data.checked === true) {
        data.type = 0;
      }
    });
  }


}
